import { PageContainer, View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useUpdateEffect } from "ahooks";

import ByRow from "@/components/ui/ByRow";
import Page from "@/components/common/Page";
import Card from "@/components/common/Card";
import ByCell from "@/components/ui/ByCell";
import ByButton from "@/components/ui/ByButton";
import ByImageGroup from "@/components/ui/ByImageGroup";
import CustomerCard from "@/components/app/CustomerCard";
import ApprovalaProcess from "@/components/app/ApprovalaProcess";

import ApiCrm from "@/api/crm";
import ApiWorkflow from "@/api/workflow";

import useFetch from "@/hooks/useFetch";
import useApproval from "@/hooks/useApproval";

import { TaskDetail } from "@/types/global";
import { IntentCustomerData } from "@/types/customer";

const Details = ({ source }: { source: any }) => {
  const keys = Object.keys(source);

  return (
    <View className="mb-2 bg-page rounded-md p-2">
      {keys.map((item, index) => (
        <ByCell label={item} key={index} size="small" labelWidth="8em">
          {source[item]}
        </ByCell>
      ))}
    </View>
  );
};

const objKeys = ["Files", "Details"];

const InstanceItem = ({
  source,
}: {
  source: TaskDetail["instanceData"][number];
}) => {
  const { caption, name, value } = source;

  const vertical = objKeys.includes(name);
  const content = vertical && value ? JSON.parse(value) : value;

  return (
    <ByCell vertical={vertical} label={caption} size="small">
      <View className="w-full">
        {value ? (
          name === "Files" ? (
            <ByImageGroup urls={content} />
          ) : name === "Details" ? (
            content.map((item, index) => <Details source={item} key={index} />)
          ) : (
            value
          )
        ) : (
          ""
        )}
      </View>
    </ByCell>
  );
};

export default () => {
  const { params } = useRouter();

  const { data, refresh } = useFetch<TaskDetail>(ApiWorkflow.detail, {
    showLoading: true,
    defaultParams: [{ workflowInstanceId: Number(params.wl_id) }],
  });

  const { data: customerData } = useFetch<{
    intentCustomer: IntentCustomerData;
  }>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId: Number(params.intentCustomerId) }],
  });

  useUpdateEffect(() => {
    if (data) {
      Taro.setNavigationBarTitle({
        title: data.workflowDefinitionName,
      });
    }
  }, [data]);

  const {
    visible,
    approverNode,
    PopupApproval,
    setApproveNode,
    onApproved,
    onRejected,
    onCancal,
  } = useApproval(refresh);

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          approverNode && (
            <ByRow>
              <ByButton
                type="error"
                size="large"
                variant="filled"
                className="w-1/3"
                onClick={onRejected}
              >
                驳回
              </ByButton>
              <ByButton size="large" className="w-1/2" onClick={onApproved}>
                通过
              </ByButton>
            </ByRow>
          )
        }
      >
        <CustomerCard source={customerData?.intentCustomer} />

        <Card className="m-3">
          {data?.instanceData.map((item, index) => (
            <InstanceItem key={index} source={item} />
          ))}
        </Card>

        <Card className="m-3">
          {data && (
            <ApprovalaProcess
              showTitle
              source={data}
              onChangeStatus={setApproveNode}
            />
          )}
        </Card>
      </Page>

      <PageContainer round show={visible} onAfterLeave={onCancal}>
        <PopupApproval />
      </PageContainer>
    </>
  );
};
